<template>
  <div class="login-container">
    <div class="background">
      <el-card class="login-card">
        <h2 class="login-title">登录</h2>
        <el-form
            :model="loginForm"
            :rules="loginRules"
            ref="loginFormRef"
            label-width="80px"
            class="login-form"
        >
          <el-form-item label="用户名" prop="username">
            <el-input
                v-model="loginForm.username"
                placeholder="请输入用户名"
                prefix-icon="el-icon-user"
            />
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input
                v-model="loginForm.password"
                type="password"
                placeholder="请输入密码"
                prefix-icon="el-icon-lock"
                show-password
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleLogin">登录</el-button>
            <el-button type="primary" @click="openRegisterDialog">注册</el-button>
            <el-button @click="resetLoginForm">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 注册对话框 -->
      <el-dialog title="注册" v-model="registerDialogVisible" :before-close="handleClose" width="30%">
        <el-form
            :model="registerForm"
            :rules="registerRules"
            ref="registerFormRef"
            label-width="80px"
            class="login-form"
        >
          <el-form-item label="用户名" prop="username">
            <el-input
                v-model="registerForm.username"
                placeholder="请输入用户名"
                prefix-icon="el-icon-user"
            />
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input
                v-model="registerForm.password"
                type="password"
                placeholder="请输入密码"
                prefix-icon="el-icon-lock"
                show-password
            />
          </el-form-item>
          <el-form-item label="确认密码" prop="password2">
            <el-input
                v-model="registerForm.password2"
                type="password"
                placeholder="请确认密码"
                prefix-icon="el-icon-lock"
                show-password
            />
          </el-form-item>
          <el-form-item label="姓名" prop="name">
            <el-input
                v-model="registerForm.name"
                placeholder="请输入姓名"
                prefix-icon="el-icon-user"
            />
          </el-form-item>
          <el-form-item label="年龄" prop="age">
            <el-input-number
                v-model="registerForm.age"
                :min="0"
                :max="150"
                placeholder="请输入年龄"
            />
          </el-form-item>
<!--          前台注册默认只能是 患者身份-->
<!--          <el-form-item label="角色" prop="role">-->
<!--            <el-select v-model="registerForm.role" placeholder="请选择角色">-->
<!--            &lt;!&ndash;&ndash;&gt;-->
<!--              <el-option label="患者" value="3"></el-option>-->
<!--            </el-select>-->
<!--          </el-form-item>-->
          <el-form-item label="证件号" prop="certId">
            <el-input
                v-model="registerForm.certId"
                placeholder="请输入证件号"
                prefix-icon="el-icon-document"
            />
          </el-form-item>
          <el-form-item label="性别" prop="sex">
            <el-radio-group v-model="registerForm.sex">
              <el-radio :label="1">男</el-radio>
              <el-radio :label="0">女</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="地址" prop="address">
            <el-input
                v-model="registerForm.address"
                placeholder="请输入地址"
                prefix-icon="el-icon-location"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleRegister">注册</el-button>
            <el-button @click="resetRegisterForm">重置</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';
import axios from '@/axios/index';

const router = useRouter();

const loginForm = ref({
  username: '',
  password: '',
});

const registerForm = ref({
  address: '',
  age: 0,
  certId: '',
  name: '',
  password: '',
  password2: '',
  role: 3,
  sex: 0,
  username: '',
});

const validatePassword = (rule, value, callback) => {
  if (value !== registerForm.value.password) {
    callback(new Error('两次输入的密码不一致!'));
  } else {
    callback();
  }
};

const loginRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少为6位', trigger: 'blur' },
  ],
};

const registerRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少为6位', trigger: 'blur' },
  ],
  password2: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    { validator: validatePassword, trigger: 'blur' },
  ],
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
  ],
  age: [
    { required: true, message: '请输入年龄', trigger: 'blur' },
    { type: 'number', message: '年龄必须是数字', trigger: 'blur' },
  ],
  certId: [
    { required: true, message: '请输入证件号', trigger: 'blur' },
      //TODO 正则表达式 验证证件号 身份证号吗
  ],
  role: [
    { required: true, message: '请选择角色', trigger: 'blur' },
  ],
  sex: [
    { required: true, message: '请选择性别', trigger: 'blur' },
  ],
  address: [
    { required: true, message: '请输入地址', trigger: 'blur' },
  ],
};



const loginFormRef = ref(null);
const registerFormRef = ref(null);
const registerDialogVisible = ref(false);

const resetLoginForm = () => {
  loginForm.value.username = '';
  loginForm.value.password = '';
  loginFormRef.value.clearValidate();
};

const resetRegisterForm = () => {
  registerForm.value.name = '';
  registerForm.value.password = '';
  registerForm.value.password2 = '';
  registerForm.value.sex = 0;
  registerForm.value.username = '';
  registerForm.value.address = '';
  registerForm.value.age = 0;
  registerForm.value.certId = '';
  registerForm.value.role = 3;
  registerFormRef.value.clearValidate();
};


// 3患者 2医生 1管理员



const handleLogin = () => {
  loginFormRef.value.validate((valid) => {
    if (valid) {
      axios.post('/user/login', loginForm.value)
          .then((response) => {
            if (response.data.code == 200) {
              ElMessage.success('登录成功');
              localStorage.setItem('token', response.data.data);
              console.log(response.data.data)
              localStorage.setItem('username', loginForm.value.username);
              // TODO 登录成功根据角色跳转到不同的页面
              router.push('/admin');
            } else {
              ElMessage.error(response.data.message);
            }
          })
          .catch((error) => {
            ElMessage.error('登录失败，请重试');
            console.error(error);
          });
    } else {
      ElMessage.error('请检查表单信息');
      return false;
    }
  });
};

const openRegisterDialog = () => {
  registerDialogVisible.value = true;
};

const handleClose = () => {
  resetRegisterForm();
  registerDialogVisible.value = false;
};

const handleRegister = () => {

  registerFormRef.value.validate((valid) => {
    if (valid) {
      registerForm.value.role = 3;
      axios.post('/user/register', registerForm.value)
          .then((response) => {
            if (response.data.code === 200) {
              ElMessage.success('注册成功');
              registerDialogVisible.value = false;
              // 可以选择跳转到登录页面或其他页面
              router.push('/login');
            } else {
              ElMessage.error(response.data.message);
            }
          })
          .catch((error) => {
            ElMessage.error('注册失败，请重试');
            console.error(error);
          });
    } else {
      ElMessage.error('请检查表单信息');
      return false;
    }
  });
};
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}

.background {
  position: fixed;
  width: 100%;
  height: 100%;
  z-index: 1;
  top: 0;
  left: 0;
  background-image: url('/src/assets/imgs/background.png');
  background-size: cover; /* 确保背景图片铺满容器 */
  background-position: center; /* 背景图片居中 */
}

.login-card {
  position: relative;
  margin-left: 15%;
  margin-top: 15%;
  width: 400px;
  padding: 20px;
  border-radius: 8px;
  background-color: #e0f7fa; /* 设置卡片背景色 */
  border: 1px solid #b2ebf2; /* 设置卡片边框颜色 */
}

.login-title {
  text-align: center;
  margin-bottom: 20px;
  font-size: 24px;
  color: #303133;
}

.login-form {
  margin-top: 20px;
}
</style>
